package com.sleepcamel.rest.domain;

import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.sleepcamel.rest.domain.util.MiscUtils;

public class Mapping extends TreeNode implements IEncodable, IImportDependant, IProducer, IConsumer, IPathable, ISourceCodeGenerable{

	private Path path;
	private boolean encodable = false;
	private List<String> produces = new ArrayList<String>();
	private List<String> consumes = new ArrayList<String>();
	
	public Mapping() {
		setName("NewMapping");
		setPath(new Path("mapping"));
	}
	
	public Path getPath() {
		return path;
	}
	
	public void setPath(Path path) {
		this.path = path;
	}

	public Set<String> getInterfaceImports(){
		Set<String> imports = new HashSet<String>();
		imports.add("javax.ws.rs.Path");
		
		if ( encodable )
			imports.add("javax.ws.rs.Encoded");

		if ( !produces.isEmpty() )
			imports.add("javax.ws.rs.Produces");
		
		if ( !consumes.isEmpty() )
			imports.add("javax.ws.rs.Consumes");
		
		List<BaseMethod<?>> methods = getChilds();
		for(BaseMethod<?> method:methods)
			imports.addAll(method.getInterfaceImports());
		return imports;
	}
	
	public Set<String> getClassImports(){
		Set<String> imports = new HashSet<String>();
		List<BaseMethod<?>> methods = getChilds();
		for(BaseMethod<?> method:methods)
			imports.addAll(method.getClassImports());
		return imports;
	}

	@Override
	public boolean isEncodable() {
		return encodable ;
	}

	public void setEncodable(boolean encodable) {
		this.encodable = encodable;
	}
	
//	public String getFullPackageName() {
//		StringBuilder sb = new StringBuilder();
//		
//		if ( parent != null && parent.getPackageName() != null ) sb.append(parent.getPackageName()).append(".");
//
//		sb.append(getPackageName());
//		return sb.toString();
//	}

	public String getSourceClassName() {
		String validName = getValidName();
		return validName.endsWith(".java")? validName : validName+".java";
	}
	
	public String getValidName() {
		return MiscUtils.getValidName(getName(),false);
	}

	@Override
	public List<String> getConsumes() {
		return consumes;
	}

	@Override
	public List<String> getProduces() {
		return produces;
	}
	
	@Override
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		super.addPropertyChangeListener(listener);
		path.addPropertyChangeListener(listener);
	}
	
	@Override
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		super.removePropertyChangeListener(listener);
		path.removePropertyChangeListener(listener);
	}

	public String getPackageName() {
		ProjectPackage projectPackage = getParent();
		return projectPackage.getPackageName();
	}
}
